package com.basic.modules.nykf.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.basic.common.utils.PageUtils;
import com.basic.common.utils.ParamsModel;
import com.basic.common.utils.Query;
import com.basic.common.utils.R;
import com.basic.modules.nykf.dao.ConsultationRecordsGjDao;
import com.basic.modules.nykf.entity.ConsultationRecordsEntity;
import com.basic.modules.nykf.entity.ConsultationRecordsGjEntity;
import com.basic.modules.nykf.entity.FileNewEntity;
import com.basic.modules.nykf.service.ConsultationRecordsGjService;
import com.basic.modules.nykf.service.ConsultationRecordsService;
import com.basic.modules.nykf.service.FileNewService;
import com.basic.modules.sys.entity.SysUserEntity;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

@Service("consultationRecordsGjService")
public class ConsultationRecordsGjServiceImpl extends ServiceImpl<ConsultationRecordsGjDao, ConsultationRecordsGjEntity> implements ConsultationRecordsGjService {

    @Lazy
    @Autowired
    ConsultationRecordsService consultationRecordsService;

    @Autowired
    FileNewService fileNewService;

    @Override
    public R saveData(ConsultationRecordsGjEntity consultationRecordsGjEntity) {
        // 校验跟进日期
        R r = gjsjCheck(consultationRecordsGjEntity);
        if (Integer.parseInt(r.get("code").toString()) == 500) {
            return r;
        }

        Object object = SecurityUtils.getSubject().getPrincipal();
        SysUserEntity sysUser = (SysUserEntity) object;
        consultationRecordsGjEntity.setCreateUserId(sysUser.getUserId());
        boolean save = this.save(consultationRecordsGjEntity);

        Long gjjlId = consultationRecordsGjEntity.getGjjlId();

        if (save) {
            // 更新咨询记录的当前节点
            UpdateWrapper<ConsultationRecordsEntity> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda()
                    .eq(ConsultationRecordsEntity::getZxid, consultationRecordsGjEntity.getZxid())
                    .set(ConsultationRecordsEntity::getDqjdVal, consultationRecordsGjEntity.getDqjdVal())
                    .set(ConsultationRecordsEntity::getDqjdName, consultationRecordsGjEntity.getDqjdName());
            consultationRecordsService.update(updateWrapper);

            // 附件
            if (consultationRecordsGjEntity.getFileIds() != null && !"".equals(consultationRecordsGjEntity.getFileIds())) {
                consultationRecordsGjEntity.setFileIds(consultationRecordsGjEntity.getFileIds().substring(1));
                String fileIds = consultationRecordsGjEntity.getFileIds();
                String[] fileIdsArray = fileIds.split(",");
                for (String id : fileIdsArray) {
                    UpdateWrapper<FileNewEntity> updateWrapper1 = new UpdateWrapper<>();
                    updateWrapper1.lambda()
                            .eq(FileNewEntity::getYkfFileId, id)
                            .set(FileNewEntity::getGlId, gjjlId);
                    fileNewService.update(updateWrapper1);
                }
            }
            return R.ok();
        }
        return R.error();
    }

    @Override
    public R updateData(ConsultationRecordsGjEntity consultationRecordsGjEntity) {
        // 校验跟进日期
        R r = gjsjCheck(consultationRecordsGjEntity);
        if (Integer.parseInt(r.get("code").toString()) == 500) {
            return r;
        }

        boolean update = this.updateById(consultationRecordsGjEntity);
        if (update) {
            // 更新咨询记录的当前节点
            UpdateWrapper<ConsultationRecordsEntity> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda()
                    .eq(ConsultationRecordsEntity::getZxid, consultationRecordsGjEntity.getZxid())
                    .set(ConsultationRecordsEntity::getDqjdVal, consultationRecordsGjEntity.getDqjdVal())
                    .set(ConsultationRecordsEntity::getDqjdName, consultationRecordsGjEntity.getDqjdName());
            consultationRecordsService.update(updateWrapper);
            return R.ok();
        }
        return R.error();
    }

    /**
     * 跟进时间校验
     *
     * @return
     */
    public R gjsjCheck(ConsultationRecordsGjEntity consultationRecordsGjEntity) {
        // 校验跟进日期
        ConsultationRecordsEntity consultationRecordsEntity = new ConsultationRecordsEntity();
        consultationRecordsEntity.setZxid(consultationRecordsGjEntity.getZxid());
        List<ConsultationRecordsGjEntity> consultationRecordsGjList = consultationRecordsService.getGjListByZxId(consultationRecordsEntity);

        // 编辑
        if (consultationRecordsGjEntity.getGjjlId() != null) {
            // 只能编辑最新的一条更近记录
            if (consultationRecordsGjList.get(0).getGjjlId() != consultationRecordsGjEntity.getGjjlId()) {
                return R.error("只能更新一条跟进记录");
            }

            // 最新一次的更近记录的跟进时间不能小于上一次的更近时间,保证有上一条
            if (consultationRecordsGjList.size() > 1 && consultationRecordsGjEntity.getGjsj().compareTo(consultationRecordsGjList.get(1).getGjsj()) < 0) {
                return R.error("更近时间不能小于上一次更新的时间");
            }
        } else {
            // 最新一次的更近记录的跟进时间不能小于上一次的更近时间,保证有上一条
            if (consultationRecordsGjList.size() > 0 && consultationRecordsGjEntity.getGjsj().compareTo(consultationRecordsGjList.get(0).getGjsj()) < 0) {
                return R.error("更近时间不能小于上一次更新的时间");
            }
        }
        return R.ok();
    }

    public static double calculateFillRate(Object obj) {
        Field[] fields = obj.getClass().getDeclaredFields();

        // 参与检测的属性
        List jcList = new ArrayList();
        jcList.add("zxdpptVal");
        jcList.add("zxdpmc");
        jcList.add("zxdplmVal");
        jcList.add("zxdpdjVal");
        jcList.add("zxywtxVal");
        jcList.add("zxywlxVal");
        jcList.add("zxfwbcVal");
        jcList.add("zxsfmsVal");
        jcList.add("sfbjVal");
        jcList.add("bjje");
        jcList.add("zxlxr");
        jcList.add("lxrsjh");
        jcList.add("qtlxfs");
        jcList.add("zycd");
        jcList.add("bjmxjqt");
        jcList.add("zxdpcs");
        jcList.add("zxdpkdVal");
        jcList.add("zxdpxlVal");
        jcList.add("zxdpflVal");
        jcList.add("zxl");
        jcList.add("zhl");
        jcList.add("pjxy");
        jcList.add("myd");
        jcList.add("tksc");

        // 需要检测的属性总数25个
        int totalFields = jcList.size();
        int nullFields = 0;

        for (Field field : fields) {
            String name = field.getName();
            if (jcList.contains(name)) {
                try {
                    field.setAccessible(true);
                    if (field.get(obj) != null) {
                        nullFields++;
                    }

                    if ("zycd".equals(name) && (Integer) field.get(obj) == 0) {
                        nullFields--;
                    }

                } catch (IllegalAccessException e) {
                    nullFields++;
                }
            }
        }
        double tcl = (double) nullFields / totalFields * 100;
        return tcl;
    }

    @Override
    public PageUtils getConsultationGjjlList(ParamsModel<ConsultationRecordsGjEntity> params) {
        IPage<ConsultationRecordsGjEntity> page = new Query<ConsultationRecordsGjEntity>().getPage(BeanUtil.beanToMap(params.getPage()));
        int pageIndex = ((int) page.getCurrent() - 1) * (int) page.getSize();
        int pageSize = (int) page.getSize();
        List<ConsultationRecordsGjEntity> consultationGjjlList = baseMapper.getConsultationGjjlList(pageIndex, pageSize, params.getCondition());
        int totalCount = baseMapper.getConsultationGjjlListCount(params.getCondition());
        return new PageUtils(consultationGjjlList, totalCount, (int) page.getSize(), (int) page.getCurrent());
    }

    public static void main(String[] args) {
        ConsultationRecordsGjEntity consultationRecordsGjEntity = new ConsultationRecordsGjEntity();
        calculateFillRate(consultationRecordsGjEntity);
    }
}